package com.snu.liwei.lyl_api.controller;

import com.snu.liwei.lyl_api.entity.Create;
import com.snu.liwei.lyl_api.entity.Gene;
import com.snu.liwei.lyl_api.entity.Pattern;
import com.snu.liwei.lyl_api.service.CreateService;
import com.snu.liwei.lyl_api.service.GeneService;
import com.snu.liwei.lyl_api.tools.UMsg;
import com.snu.liwei.lyl_api.tools.Xml2JsonUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = {"http://192.168.31.215:3000","http://127.0.0.1:3000"})
@RequestMapping(value = "Gene",produces = "application/json;charset=UTF-8")
public class GeneLibController {
    @Autowired
    GeneService geneService;

    @Autowired
    CreateService createService;

    @RequestMapping("GeneList")
    public UMsg getGeneList()
    {
        System.out.println("接口GeneList");
        List<Gene> list=geneService.getGeneList();
        return UMsg.ok(list);
    }
    @RequestMapping("PtList")
    public UMsg getPatternList()
    {
        System.out.println("接口PtList");
        List<Pattern> list=geneService.getPatternList();
        return UMsg.ok(list);
    }

    @RequestMapping(value="GeneDetail" )
    public UMsg getGeneDetail(@RequestBody Gene detail)
    {
        System.out.println("接口GeneDetail:"+detail.toString());
        String geneJson;
        if (detail.getPath()!=null)
        {
            /*如果传过来的路径不为空，则直接按路径找
            * 首先从缓存中找，如果有就直接从缓存中取
            * 没有就读取文件然后返回结果且放入缓存
            * 缓存满了需要把最早的缓存数据踢出
            * */
            File file=new File(detail.getPath());
            geneJson = Xml2JsonUtil.xml2JSON(file);
            System.out.println(geneJson);
        }
        else
        {
            geneJson=geneService.getGeneDetail(detail);
            //否则根据名称找
        }
        if (geneJson==null||geneJson.equals(' '))
        {
            return UMsg.failed();
        }
        else
            return UMsg.ok(geneJson);
    }

    @RequestMapping(value="PtDetail" )
    public UMsg getPtDetail(@RequestBody Pattern detail)
    {
        System.out.println("接口PtDetail"+detail.toString());
        if (detail.getPath()!=null)
        {
            File file=new File(detail.getPath());
            String ptJson = Xml2JsonUtil.xml2JSON(file);
            System.out.println(ptJson);
            return UMsg.ok(ptJson);
        }
        else
        {
            //否则根据名称找
        }
        //都找不到则返回失败
        return UMsg.failed();
    }

    @RequestMapping(value="GenesDetail" )
    public UMsg getGenesDetail(@RequestBody List<Gene> geneList){
        //List<String> geneJsonList=new ArrayList<>();
        Map<String,String> geneJsonMap=new HashMap<>();
        for(Gene gene:geneList)
        {
            if (gene.getPath()!=null)
            {
                File file= new File(gene.getPath());
                geneJsonMap.put(gene.getGid(),Xml2JsonUtil.xml2JSON(file));
                //geneJsonList.add(Xml2JsonUtil.xml2JSON(file));
            }
        }
        if (geneJsonMap.size()!=0)
        {
            return UMsg.ok(geneJsonMap);
        }
        else
            return UMsg.failed();
    }


    @RequestMapping(value="create" )
    public void writeDataToFile(@RequestBody Create create) throws IOException, ParseException {

        String username = create.getUsername();
        String c_name = create.getC_name();
        String pattern = create.getPattern();
        //文件目录
        File writefile;
        BufferedWriter bw;
        boolean append = true;  //  是否追加
        String path = "C:/Users/tckeke/Desktop/userCreation/"+c_name+".txt";
        //String path = "D:\\ocr.txt";
        writefile = new File(path);
        if (writefile.exists() == false)   // 判断文件是否存在，不存在则生成
        {
            try {
                writefile.createNewFile();
                writefile = new File(path);
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
        else
        {
            path = "C:/Users/tckeke/Desktop/userCreation/"+c_name+System.currentTimeMillis()+".txt";
            writefile = new File(path);
            try {
                writefile.createNewFile();
                writefile = new File(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileWriter fw = new FileWriter(writefile, append);
            bw = new BufferedWriter(fw);
            fw.write(String.valueOf(pattern));
            fw.flush();
            fw.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取当前时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());
        Date date = df.parse(time);

        //判断c_name是否已经存在数据库中
        String exist = createService.exist(c_name);
        if(exist!=null){
            createService.create(username,c_name+time,path,date);
        } else {
            createService.create(username,c_name,path,date);
        }



    }

    /**
     * 查询是服务器磁盘的json文件，封装成对象返回
     * 基因库json文件所在位置（glib.path），请随实际情况更改，
     */
    @ApiOperation("通过gid 查询对应的一个gene")
    @GetMapping("getGeneByGid")
    public Object getGeneByGid(
            @RequestParam("gid")String gid) throws Exception {
        return geneService.getGeneByGid(gid);
    }

}
